import { ChartData } from '@/types/chat';
import { Chart } from '@berryv/g2-react';
import { Card, CardContent, Typography } from '@mui/joy';
import { useRef } from 'react';
import { theme } from './theme.js';

export default function BarChart({ chart }: { key: string; chart: ChartData }) {
  const chartRef = useRef();
  function onInit() {
    const chart = chartRef.current;
    chart.theme({ ...theme });
    /* chart.axis('xField', {
      label: {
        autoRotate: false, // 关闭自动旋转，以便于控制换行
        formatter: (text, item) => {
          // 使用\n进行手动换行，或者使用一些自动换行的逻辑
          const maxLength = 4; // 假设每行最多10个字符
          if (text.length > maxLength) {
            let rows = Math.ceil(text.length / maxLength);
            let result = [];
            for (let i = 0; i < rows; i++) {
              result.push(text.slice(i * maxLength, (i + 1) * maxLength));
            }
            return result.join('\n');
          }
          return text;
        },
        offset: 10, // 可能需要调整偏移量以适应多行文本
        style: {
          textAlign: 'center', // 文本对齐方式
          textBaseline: 'middle', // 基线对齐方式
        },
      },
    }); */
    chart.render();
    
  }
  return (
    <div className="flex-1 min-w-0">
      <Card className="h-full" sx={{ background: 'transparent' }}>
        <CardContent className="h-full">
          <Typography gutterBottom component="div">
            {chart.chart_name}
          </Typography>
          <Typography gutterBottom level="body3">
            {chart.chart_desc}
          </Typography>
          <div className="h-[300px]">
            
            <Chart
              style={{ height: '100%' }}
              options={{
                autoFit: true,
                type: 'interval',
                data: chart.values,
                encode: { x: 'name', y: 'value', color: 'type' },
                axis: {
                  x: {
                    labelAutoRotate: false,
                  },
                },
              }}
              ref={chartRef}
              onInit={onInit}
            />
          </div>
        </CardContent>
      </Card>
    </div>
  );
}
